package com.bnlr.lrparking.appui.order;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bnlr.lrparking.R;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.appui.paypwd.SetPayPasswordActivity;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.constant.Urls;
import com.bnlr.lrparking.event.PaySuccee1Event;
import com.bnlr.lrparking.event.PaySucceeEvent;
import com.bnlr.lrparking.event.PayTimeEvent;
import com.bnlr.lrparking.model.StallM;
import com.bnlr.lrparking.util.CommonUtil;
import com.bnlr.lrparking.util.pwddialog.SecurityEditCompileListener;
import com.bnlr.lrparking.util.pwddialog.SecurityPasswordEditText;
import com.bnlr.lrparking.util.pwddialog.ShowType;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.flyco.animation.BounceEnter.BounceTopEnter;
import com.flyco.animation.SlideExit.SlideBottomExit;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.kyleduo.switchbutton.SwitchButton;
import com.yolanda.nohttp.NoHttp;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import cn.iwgang.countdownview.CountdownView;

/**
 * Created by hp on 2017/8/17.
 * 支付订单
 */

public class OrderPayActivity extends BaseActivity implements CountdownView.OnCountdownEndListener{

    String paypassword;
    public static ShowType showType = ShowType.hideNumber;
    private TextView tvNavTitle;
    private RelativeLayout rely_gx;
    private TextView tv_okpay_btn;
    private long minute = 1000*60*15;//15分钟
    private CountdownView mCvCountdownView;

    private String orderNo,money;
    private AlertDialog paydialog;
    private TextView tv_dollor;
    private SwitchButton mDefaultSb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_pay);
        initView();
    }

    private void initView(){

        mCvCountdownView=(CountdownView)findViewById(R.id.cv_countdownViewTest1);
        Intent intent=getIntent();
        if (AppConfig.getInstance().getString("isList", "").equals("1")) {
            long dataResult = Long.parseLong(AppConfig.getInstance().getString("dataResult", ""));//用户名
            if (dataResult > 0) {
                mCvCountdownView.start(dataResult);
            } else {
                minute = 0;
                mCvCountdownView.start(minute);
            }
        }else {
            mCvCountdownView.start(minute);
        }
        EventBus.getDefault().register(this);//
        orderNo=intent.getStringExtra("orderNo");
        money=intent.getStringExtra("money");
        tvNavTitle=(TextView)findViewById(R.id.tv_nav_title);
        tv_dollor=(TextView)findViewById(R.id.tv_dollor);
        tv_dollor.setText(money);
        tvNavTitle.setText("支付订单");
        rely_gx=(RelativeLayout)findViewById(R.id.rely_gx);
        tv_okpay_btn=(TextView)findViewById(R.id.tv_okpay_btn);
        rely_gx.setOnClickListener(this);
        mDefaultSb = (SwitchButton) findViewById(R.id.sb_default);
        mDefaultSb.setCheckedImmediatelyNoEvent(false);
        // Millisecond
        mCvCountdownView.setOnCountdownEndListener(this);
        for (int time=0; time<1000; time++) {
            mCvCountdownView.updateShow(time);
        }
        tv_okpay_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                    isSetPayPassword();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        paypassword=AppConfig.getInstance().getString("paypassword", "");
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPaySuccessEvent(PaySucceeEvent event) {
        finish();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPaySuccess1Event(PaySuccee1Event event) {
        finish();
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){

        }
    }
    /*@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            if(showType == ShowType.hideNumber){
                showType = ShowType.showNumber;
            }else{
                showType = ShowType.hideNumber;
            }
            return true;
        }
        return super.onOptionsItemSelected(item);
    }*/

    /**
     * 支付弹框
     */
    public void showPayDialog() {
        paydialog = new AlertDialog.Builder(this).create();
        paydialog.setCanceledOnTouchOutside(false);
        paydialog.show();
        Window window = paydialog.getWindow();
        window.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        window.setContentView(R.layout.activity_input_password_dialog);
        final RelativeLayout pay_back=(RelativeLayout)window.findViewById(R.id.pay_back);
//        final TextView forget_pwd=(TextView)window.findViewById(R.id.forget_pwd);
        pay_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                paydialog.dismiss();
            }
        });
//        forget_pwd.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                startActivity(ForgetPayPwdActivity.class);
//            }
//        });
        final SecurityPasswordEditText editSecurityCode = (SecurityPasswordEditText) window
                .findViewById(R.id.security_linear);
        editSecurityCode.setSecurityEditCompileListener(new SecurityEditCompileListener() {
            @Override
            public void onNumCompleted(String num) {
                getPay(num);
            }
        });
    }
    //这个是判断是不是已经设置支付密码
    private void isSetPayPassword(){
        if (paypassword.equals("1")) {
            showPayDialog();
        }else if (paypassword.equals("0")){
            final NormalDialog dialog = new NormalDialog(baseContext);
            dialog.title("安全提示")
                    .titleTextColor(baseContext.getResources().getColor(R.color.black_color))
                    .titleTextSize(15)
                    .content("您还没有支付密码，请先设置！")
                    .contentTextSize(15)
                    .contentTextColor(baseContext.getResources().getColor(R.color.gray_color))
                    .btnText("取消", "设置")
                    .btnNum(2)
                    .style(NormalDialog.STYLE_TWO)
                    .btnTextColor(baseContext.getResources().getColor(R.color.gray_color), baseContext.getResources().getColor(R.color.colorAccent))
                    .btnTextSize(15, 15)
                    .widthScale(0.8f)//
                    .showAnim(new BounceTopEnter())//
                    .dismissAnim(new SlideBottomExit())//
                    .cornerRadius(7)
                    .show();
            dialog.setCancelable(true);
            dialog.setOnBtnClickL(
                    new OnBtnClickL() {
                        @Override
                        public void onBtnClick() {
                            dialog.dismiss();
                        }
                    },
                    new OnBtnClickL() {
                        @Override
                        public void onBtnClick() {
                            dialog.dismiss();
                            startActivity(SetPayPasswordActivity.class);
                        }
                    });
        }
    }
    //倒计时结束
    @Override
    public void onEnd(CountdownView cv) {
        EventBus.getDefault().post(new PayTimeEvent());
        finish();
    }
    //支付接口
    private void getPay(String payPwd){
        try {
            mRequest = NoHttp.createStringRequest(Urls.SPACE_IP, LrConstant.POST);
            mRequest.add("action", "PayForApply");
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("orderNo", orderNo);
            mRequest.add("payPwd", payPwd);

            CallServer.getRequestInstance().add(baseContext, mRequest,
                    new CustomHttpListener<StallM>(baseContext, true, StallM.class) {
                        @Override
                        public void doWork(StallM data, String code) {
                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {

                            try {
                                super.onFinally(obj, code, isSucceed);
                                if (code.equals("1")) {
                                    startActivity(PaySucceedActivity.class);
                                    paydialog.dismiss();
                                }else if (code.equals("0")){
                                    CommonUtil.showToask(baseContext, obj.getString("msg"));
                                    paydialog.dismiss();
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, true);
        } catch (Exception e) {

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
//    /**
//     * 获取用户信息
//     */
//    private void getPersonInfo() {
//        try {
//            mRequest = NoHttp.createStringRequest(Urls.IP, LrConstant.POST);
//            mRequest.add("action", "GetUserInfoById");
//            mRequest.add("phonePara",Application.DEVICE_ID);
//            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
//            // 添加到请求队列
//            CallServer.getRequestInstance().add(OrderPayActivity.this, mRequest,
//                    new CustomHttpListener<JSONObject>(OrderPayActivity.this, false, null) {
//                        @Override
//                        public void doWork(JSONObject data, String code) {
//                        }
//                        @Override
//                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
//                            try {
//                                super.onFinally(obj, code, isSucceed);
//                                if ("1".equals(code)) {
//                                    JSONObject object = obj.getJSONObject("data");
//                                    paypassword=object.getString("paypassword");//是不是设置过支付密码
//                                }
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                            }
//                        }
//                    }, false);
//        } catch (Exception e) {
//        }
//    }
}
